'use strict';
const fs = require('fs');
const inquirer = require('inquirer');
const fse = require('fs-extra');
const semver = require('semver');
const Command = require('@dpx-cli-dev/command');
const log = require('@dpx-cli-dev/log');
const getProjectTemplate = require('./getProjectTemplate');
const TYPE_PROJECT = 'project';
const TYPE_COMPONENT = 'component';
class InitCommand extends Command {
  init() {
    // this.projectName = this._argv[0] || '';
    // this.force = !!this._cmd.force;
    // log.verbose(this.projectName);
    // log.verbose(this.force);
  }
  async exec() {
    try {
      // 1.准备阶段
      const projectInfo = await this.prepare();
      if (projectInfo) {
        log.verbose('projectInfo', projectInfo);
        this.projectInfo = projectInfo;
        // 2.下载模板
        this.downloadTemplate();
        // 3.安装模板
      }
    } catch (e) {
      log.error(e.message);
    }
  }
  async prepare() {
    // 0. 判断项目模板是否存在
    const template = await getProjectTemplate();
    if (!template || template.length === 0) {
      throw new Error('项目模板不存在');
    }
    this.template = template;
    const localPath = process.cwd();
    if (!this.isDirEmpty(localPath)) {
      let ifContinue = false;
      if (!this.force) {
        ifContinue = (
          await inquirer.prompt([
            {
              type: 'confirm',
              name: 'ifContinue',
              default: false,
              message: '当前文件夹不为空，是否继续创建项目？',
            },
          ])
        ).ifContinue;
        if (!ifContinue) {
          return;
        }
      }
      if (ifContinue || this.force) {
        // 给用户做二次确认
        const { confirmDelete } = await inquirer.prompt({
          type: 'confirm',
          name: 'confirmDelete',
          default: false,
          message: '是否确认清空当前目录下的文件？',
        });
        if (confirmDelete) {
          // 清空当前目录
          // fse.removeSync()
          fse.emptyDirSync(localPath);
        }
      }
    }
    return this.getProjectInfo();
  }
  downloadTemplate() {
    // 1.通过项目模板API获取项目模板信息
    console.log(this.projectInfo, this.template, 'ddd');
    // 1.1 通过egg.js搭建一套后端系统
    // 1.2 通过npm存储项目模板 vue-cli vue-element-admin
    // 1.3 将下那个木模板信息存储到mongodb数据库中
    // 1.4 通过egg.js获取mongodb中的数据并且通过API返回
  }
  async getProjectInfo() {
    let projectInfo = {};
    // 1.选择创建项目或组件
    const { type } = await inquirer.prompt({
      type: 'list',
      name: 'type',
      message: '请选择初始化类型',
      default: TYPE_PROJECT,
      choices: [
        {
          name: '项目',
          value: TYPE_PROJECT,
        },
        {
          name: '组件',
          value: TYPE_COMPONENT,
        },
      ],
    });
    log.verbose('type', type);
    // 2.获取项目的基本信息
    if (type === TYPE_PROJECT) {
      const project = await inquirer.prompt([
        {
          type: 'input',
          name: 'projectName',
          message: '请输入项目名称',
          default: '',
          validate: function (v) {
            const done = this.async();
            setTimeout(function () {
              const reg =
                /^[a-zA-Z]+([-][a-zA-Z][a-zA-Z0-9]*|[_][a-zA-Z0-9]*|[a-zA-Z0-9])*$/;
              if (!reg.test(v)) {
                done('请输入合法的项目名称');
                return;
              }
              done(null, true);
            }, 0);
            // 1 输入的首字符和尾字符必须为字符
            // 2 尾字符必须为英文或数字、不能为字符
            // 3 字符仅允许 -_
            // return /^[a-zA-Z]+[\w-]*[a-zA-Z0-9]$/
            // return;
          },
          filter: function (v) {
            return v;
          },
        },
        {
          type: 'input',
          name: 'projectVersion',
          message: '请输入项目版本号',
          default: '1.0.0',
          validate: function (v) {
            return !!semver.valid(v);
          },
          filter: function (v) {
            if (!!semver.valid(v)) {
              return semver.valid(v);
            }
            return v;
          },
        },
        {
          type: 'list',
          name: 'projectTemplate',
          message: '请选择项目模板',
          choices: this.createTemplateChoice(),
        },
      ]);
      projectInfo = {
        type,
        ...project,
      };
    } else if (type === TYPE_COMPONENT) {
    }
    // return 项目的基本信息 (object)
    return projectInfo;
  }
  createTemplateChoice() {
    return this.template.map((item) => ({
      name: item.name,
      value: item.npmName,
    }));
  }
  isDirEmpty(localPath) {
    // path.resolve('.')
    let fileList = fs.readdirSync(localPath);
    fileList = fileList.filter(
      (file) => !file.startsWith('.') && ['node_modules'].indexOf(file) < 0
    );
    return !fileList || fileList.length <= 0;
  }
}
function init(argv) {
  // console.log('init', projectName, comObj.force, process.env.CLI_TARGET_PATH);
  // console.log(argv)
  // const test = argv[argv.length - 2];
  // console.log(test)
  return new InitCommand(argv);
}
module.exports.InitCommand = InitCommand;
module.exports = init;
